package com.example.demo.Controller;

import com.example.demo.pojo.UserInfo;
import com.example.demo.service.impl.UserInfoServiceImpl;
import com.example.demo.utils.LoggerConfig;
import com.example.demo.utils.RedisUtil;
import com.example.demo.utils.ResultCode;
import com.example.demo.configuration.TokenProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.*;

@Controller
public class HomeController {

    @Autowired
    ApplicationContext context;

    @Autowired
    UserInfoServiceImpl userInfoService;

    @Autowired
    RedisUtil redisUtil;

    @RequestMapping("/login.html")
    public String home() {
        return "login";
    }

    @RequestMapping("/register.html")
    public String register() {
        return "register";
    }

    @ResponseBody
    @RequestMapping(value = "/register/addUser")
    public Map<String, Object> registerUserInfo(@Valid UserInfo userInfoModel, BindingResult bindingResult) {
        // 判断格式是否都正确
        Map<String, Object> result = new LinkedHashMap<>();
        boolean flag = bindingResult.hasErrors();
        if (flag) {
            List<FieldError> errorMessage = bindingResult.getFieldErrors();
            for (FieldError fieldError : errorMessage) {
                result.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            result.put("result", ResultCode.getResultFalse());
            LoggerConfig.getLoggerInfo("参数格式错误");
        } else {
            if (userInfoService.addUserInfo(userInfoModel)) {
                result.put("result", ResultCode.gertResultSuccess());
                result.put("msg", "注册成功");
                LoggerConfig.getLoggerInfo("注册成功");
            } else {
                result.put("result", ResultCode.getResultFalse());
                result.put("msg", "手机号已注册");
                LoggerConfig.getLoggerInfo("注册失败");
            }
        }
        return result;
    }

    /**
     * 测试参数
     */
    @ResponseBody
    @RequestMapping(value = "/count")
    public void testRedis() {
        redisUtil.setKeyWithTime("test", "a", 10);
        redisUtil.delete(new String[]{"test", "aaa"});
        LoggerConfig.getLoggerInfo(String.valueOf(redisUtil.get("test")));
    }

    @ResponseBody
    @RequestMapping(value = "/user/login")
    public Map<String, Object> login(String mobile, String passWord, HttpServletResponse httpResponse) throws Exception {
        Map<String, Object> msg = new HashMap<>();
        // 查询不到注册手机号
        if(!userInfoService.queryPhone(String.valueOf(mobile))){
            msg.put("msg","手机号未注册");
            return msg;
        };
        // 只会有一条数据产生
        List<UserInfo> userInfoModel = userInfoService.login(mobile, passWord);
        if (userInfoModel.size() != 1) {
            msg.put("msg", "用户名或者密码错误");
        }
        if (userInfoModel.size() == 1) {
            // 当前系统只存在唯一一条数据时
            String token = TokenProducer.getToken(mobile);
            if (token != null) {
                LoggerConfig.getLoggerInfo("登录时产生的token:" + token);
                redisUtil.setKeyWithTime(token, userInfoModel.get(0).getId(), 10000);
                Cookie cookie = new Cookie("token", token);
                httpResponse.addCookie(cookie);
                msg.put("msg", "登录成功");
                msg.put("result", ResultCode.gertResultSuccess());
                msg.put("userInfo", userInfoModel.get(0).getId());
                msg.put("token", token);
            } else {
                msg.put("msg", "token生成失败");
            }
        }
        return msg;
    }

    @RequestMapping("/test.html")
    public String getTest(Map<Object,String> map){
        map.put("name","1111");
        map.put("age","1111");
        return "test";
    }
}
